package com.plugins.http;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;
import com.iclient.dao.DaoUtils;
import com.iclient.dao.service.ImgService;

public class MyLogin {

	private static RequestConfig config = RequestConfig.custom()
			.setProxy(new HttpHost("127.0.0.1", 8888))
			.setCookieSpec(CookieSpecs.STANDARD)
			.setRedirectsEnabled(false)
			.build();
	
	/**
	 * 获取登录验证吗
	 * @return
	 */
	public static Map<String, String> getLoginCode(){
		HttpGet httpGet = new HttpGet("http://login.weibo.cn/login/");
		httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:33.0) Gecko/20100101 Firefox/33.0");
		httpGet.addHeader("Host", "login.weibo.cn");
		httpGet.addHeader("Origin", "https://login.weibo.cn");
		httpGet.addHeader("Referer", "https://login.weibo.cn/login/");
		CloseableHttpClient httpClient = HttpClients.createDefault();
		try{
			CloseableHttpResponse response = httpClient.execute(httpGet, HttpClientContext.create());
			if(response.getStatusLine().getStatusCode() == 200){
				String login_page = EntityUtils.toString(response.getEntity());
				Document document = Jsoup.parse(login_page);
				Element e = document.getElementsByAttributeValue("alt", "请打开图片显示").get(0);
				String action = document.getElementsByTag("form").get(0).attr("action");
				String passwordfield = document.getElementsByAttributeValue("type", "password").get(0).attr("name");
				String vk = document.getElementsByAttributeValue("name", "vk").get(0).attr("value");
				String capId = document.getElementsByAttributeValue("name", "capId").get(0).attr("value");
				Map<String, String> param = new HashMap<>();
				param.put(passwordfield, "yanghui");
				param.put("mobile", "1002318371@163.com");
				param.put("remember", "on");
				param.put("backURL", "http%3A%2F%2Fweibo.cn");
				param.put("backTitle", "手机新浪网");
				param.put("tryCount", "");
				param.put("vk", vk);
				param.put("capId", capId);
				param.put("submit", "登录");
				param.put("code", "");
				HttpGet httpGet0 = new HttpGet(e.attr("src"));
				CloseableHttpResponse response0 =  httpClient.execute(httpGet0);
				ImgService imgService = (ImgService) DaoUtils.getBean("imgService");
				String imgUrl = FileUtils.readImg(imgService, response0.getEntity().getContent());
				param.put("imgUrl", imgUrl);
				param.put("loginUrl", "http://login.weibo.cn/login/"+ action);
				httpGet.releaseConnection();
				return param;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	
	public static String doLogin(Map<String, String> param){
		String msg = "";
		CloseableHttpClient httpClient = HttpClients.createDefault();
		List<NameValuePair> pairs = new ArrayList<>();
		HttpPost httpPost = null;
		if(null != param){
			httpPost = new HttpPost(param.get("loginUrl"));
			httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:33.0) Gecko/20100101 Firefox/33.0");
			httpPost.addHeader("Host", "login.weibo.cn");
			httpPost.addHeader("Origin", "https://login.weibo.cn");
			httpPost.addHeader("Referer", "https://login.weibo.cn/login/");
			for(String key : param.keySet()){
				pairs.add(new BasicNameValuePair(key, param.get(key)));
			}
		}
		if(!CollectionUtils.isEmpty(pairs) && null != httpPost){
			try{
				httpPost.setEntity(new UrlEncodedFormEntity(pairs));
				CloseableHttpResponse response = httpClient.execute(httpPost, HttpClientContext.create());
				if(response.getStatusLine().getStatusCode() == 302){
					HttpGet httpget = new HttpGet(response.getLastHeader("Location").getValue());
					httpget.setConfig(config);
					HttpResponse resp = httpClient.execute(httpget);
					if(resp.getStatusLine().getStatusCode() == 302){
						HttpGet get = new HttpGet("http://weibo.cn");
						get.setConfig(config);
						HttpClientContext context = HttpClientContext.create();
						httpClient.execute(get, context);
						List<Cookie> cookies = context.getCookieStore().getCookies();
						msg = JSONObject.toJSONString(cookies);
						get.releaseConnection();
					}
					httpget.releaseConnection();
				}
				httpPost.releaseConnection();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return msg;
	}
	
	
}
